<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useI18n } from '@/hooks/web/useI18n'
import { reactive } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { getDepartmentApi, getDepartmentDetailApi } from '@/api/department'
import { Log } from '@/utils/logError'
import { listToTree } from '@/utils/tree'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentId: {
    type: Number,
    default: () => null
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('department.name'),
    component: 'Input'
  },
  {
    field: 'parentDeptId',
    label: t('department.parentDeptId'),
    component: 'Cascader',
    componentProps: {
      nodeKey: 'id',
      props: {
        checkStrictly: true,
        showPrefix: false,
        label: 'name',
        value: 'id'
      }
    },
    optionApi: async () => {
      const res = await getDepartmentApi()
      return listToTree(res.data, { pid: 'parentDeptId' })
    }
  },
  {
    field: 'status',
    label: t('department.status'),
    component: 'Switch'
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input'
  }
])
const rules = reactive({
  id: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, getComponentExpose } = formMethods

const getDepartmentDetail = async () => {
  try {
    if (!props.currentId) return await setValues({})
    const res = await getDepartmentDetailApi(props.currentId)
    await setValues(res.data)
  } catch (error) {
    Log.error('getDepartmentDetail', error)
  }
}
getDepartmentDetail()

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (Array.isArray(formData.parentDeptId) && formData.parentDeptId.length >= 1)
      formData.parentDeptId = formData.parentDeptId[formData.parentDeptId.length - 1]
    else delete formData.parentDeptId
    return formData
  }
}

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" :is-col="false" @register="formRegister" :schema="formSchema" />
</template>
